<template>
  <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
    <div class="content_wrap">
      <el-form ref="ruleForm" :model="dataForm" :rules="dataRules" label-width="100px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="dataForm.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="dataForm.brandId" placeholder="请选择所属品牌">
            <el-option
              v-for="item in brandList"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类" prop="productCategoryId">
          <el-select v-model="dataForm.productCategoryId" @change="handleCategory" placeholder="请选择产品分类">
            <el-option
              v-for="item in categoryList"
              :key="item.productCategoryId"
              :label="item.productCategoryName"
              :value="item.productCategoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品参数" class="detail_wrap" :style="toggleStyle" prop="details" v-if="dataForm.detailsList && dataForm.detailsList.length > 0">
          <div class="detail" v-for="(item, index) in dataForm.detailsList" :key="index">
            <el-input v-model="item.detailsMenuName" clearable style="width:23%" placeholder="请输入"></el-input>
            <el-input type="textarea" :rows="3" placeholder="请输入" clearable v-model="item.detailValue"></el-input>
            <el-button type="danger"  size="small" @click.prevent="removeDetail(item)">删除</el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="dataForm.detailsList && dataForm.detailsList.length > 0">
          <p class="toggle" @click="handleToggle" v-if="dataForm.detailsList.length > 6"  >
            <span v-if="toggleFlag">收起</span>
            <span v-else>展开</span>
          </p>
          <div class="detail_add" @click="addDetails">
            <el-button type="primary">新增</el-button>
          </div>
        </el-form-item>
        <el-form-item label="产品价格" prop="price" class="price_wrap">
          <div class="price" v-for="(item,index) in dict.type.user_level" :key="index">
            <span>{{ item.label }}</span>
            <el-input v-model="item.raw.dictValue" type="number" clearable style="width:20%" placeholder="请输入"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="产品详情">
          <editor v-model="dataForm.productInfo" :min-height="250"/>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-radio-group v-model="dataForm.isShow">
            <el-radio
              v-for="dict in dict.type.is_show"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="产品图片" prop="imgUrl">
          <ImageUpload :value=" dataForm.imgUrl ? imgUrl + dataForm.imgUrl : dataForm.imgUrl" :uploadImgUrlType="'product'" @input="inputEventListener" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { addProduct, getProduct, updateProduct, brandSelectList, categorySelectList, getProductDetail } from "@/api/product";

export default {
  name: "productAdd",
  dicts: ['is_show', 'user_level'],
  computed: {
    toggleStyle () {
      let length = this.dataForm.detailsList.length
      let height = null
      if (length < 3) {
        height = '120px'
      } else if (length < 5) {
        height = '200px'
      } else {
        height = '284px'
      }
      return this.toggleFlag ? 'height:auto' : `height:${height}`
    }
  },
  data () {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      dataForm: {
        productName: '',
        imgUrl: '',
        isShow: '0',
        productInfo:'',
        productCategoryId: undefined, // 分类id
        brandId: undefined, // 品牌id
        productId: undefined, // 产品id
        detailsList: [],
        priceList: [],
      },
      // 表单校验
      dataRules: {
        productName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
        productCategoryId: [
          { required: true, message: '请选择产品名称', trigger: 'change' },
        ],
        brandId: [
          { required: true, message: '请选择品牌名称', trigger: 'change' },
        ],
        priceList: [
          { required: false, message: '请输入金额', trigger: 'blur' },
        ],
        price: [
          { required: false, message: '请输入金额', trigger: 'blur' },
        ],
        details: [
          { required: false, message: '完善产品信息', trigger: 'blur' },
        ],
        imgUrl: [
          { required: true, message: '请上传品牌logo', trigger: 'change' },
        ]
      },

      categoryList: [],
      brandList: [],
      getProductList: [],
      toggleFlag: false
    }
  },
  methods: {
    init(e) {
      this.dict.type.user_level.forEach(el => el.raw.dictValue = '')
      this.reset();
      this.open = true;
      this.title = e ? "编辑产品" : "添加产品";
      this.dataForm.productId = e || undefined
      this.brandSelectListReq()
      this.categorySelectListReq()
      if (e) return this.handleUpdate(e)
    },
    // 品牌列表
    brandSelectListReq () {
      brandSelectList().then(res => {
        // const { code, rows, msg } = res
        // if (code != 200) return this.$modal.msgError(msg);
        this.brandList = res
      })
    },
    // 分类列表
    categorySelectListReq () {
      categorySelectList().then(res => {
        // const { code, rows, msg } = res
        // if (code != 200) return this.$modal.msgError(msg);
        this.categoryList = res
      })
    },
    // 产品分类选择
    handleCategory (e) {
      this.getProductDetailReq(e)
    },
    // 产品参数数组信息
    getProductDetailReq (productCategoryId, productId = undefined) {
      getProductDetail({ productCategoryId, productId }).then(res => {
        const { code, data, msg } = res
        if (code != 200) return this.$modal.msgError(msg);
        this.dataForm.detailsList = data;
      })
    },
    // 表单重置
    reset () {
      for (var key in this.dataForm) {
        if (Array.isArray(this.dataForm[key])) {
          this.dataForm[key] = []
        } else {
          this.dataForm[key] = ''
        }
      }
      this.dataForm.isShow = '0'
      this.resetForm("ruleForm");
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      getProduct(row).then(res => {
        const { code, data, msg } = res
        if (code != 200) return this.$modal.msgError(msg);
        this.dataForm = { ...data }
        // 产品价格数据回显
        data.priceList.forEach(element => {
          this.dict.type.user_level.forEach(el => {
            if (element.userLevel == el.value) el.raw.dictValue = element.price
          })
        })
        this.dataForm.isShow = data.isShow + ''
        // 产品参数
        let { productCategoryId, productId } = data
        this.getProductDetailReq(productCategoryId, productId)
      });
    },
    /** 提交按钮 */
    submitForm () {
      // 产品参数
      let detailsListArray = []
      this.dataForm.detailsList.forEach(element => {
        let obj = {
          detailsMenuName: '',
          detailValue: ''
        }
        obj.detailsMenuName = element.detailsMenuName
        obj.detailValue = element.detailValue
        detailsListArray.push(obj)
      })
      this.dataForm.detailsList = detailsListArray
      // 产品价格
      let priceListArray = []
      this.dict.type.user_level.forEach((element, index) => {
        let obj = {
          userLevel: '',
          price: ''
        }
        if (element.value == index + 1) {
          obj.userLevel = element.value
          obj.price = element.raw.dictValue
          priceListArray.push(obj)
        }
      });
      this.dataForm.priceList = priceListArray
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          // 产品参数必填项
          if (this.dataForm.detailsList.length > 0) {
            const detailsFlagNull = this.dataForm.detailsList.some(el => el.detailValue == null)
            const detailsFlag = this.dataForm.detailsList.some(el => el.detailValue == '')
            const detailsFlagName = this.dataForm.detailsList.some(el => el.detailsMenuName == '')
            if (detailsFlagNull) return this.$modal.msgWarning('请完善产品参数内容')
            if (detailsFlag) return this.$modal.msgWarning('请完善产品参数内容')
            if (detailsFlagName) return this.$modal.msgWarning('请完善产品参数标题')
          }
          //产品价格必填项
          const priceFlag = this.dataForm.priceList.some(el => el.price == '')
          if (priceFlag) return this.$modal.msgWarning('请完善产品价格')

          const api = this.dataForm.productId ? updateProduct(this.dataForm) : addProduct(this.dataForm)
          api.then(res => {
            const { code, msg } = res
            if (code !== 200) return this.$modal.msgError(msg);
            this.dataForm.productId ? this.$modal.msgSuccess("修改成功") : this.$modal.msgSuccess("添加成功")
            this.open = false;
            this.$emit('eventUpdata')
          })
        }
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 图片
    inputEventListener (event) {
      this.dataForm.imgUrl = event
    },
    addDetails () {
      let add = {
        createBy: null,
        createTime: null,
        detailValue: null,
        detailsMenuName: "",
        productDetailsId: null,
        productId: null,
        remark: null,
        updateBy: null,
        updateTime: null,
      }

      this.toggleFlag = true
      this.dataForm.detailsList.push(add)
    },
    removeDetail (item) {
      const index = this.dataForm.detailsList.findIndex(ele => ele.detailsMenuName === item.detailsMenuName)
      this.dataForm.detailsList.splice(index, 1)
    },
    handleToggle () {
      this.toggleFlag = !this.toggleFlag
    }
  }
}
</script>
<style lang="scss" scoped>
.content_wrap {
  // width: 100%;
}
::v-deep .el-dialog__body {
  height: 700px;
  overflow-y: auto;
}

.detail {
  min-width: 50%;
  display: flex;
  margin-bottom: 20px;
  .el-input {
    height: 36px;
  }
  .el-textarea {
    width: 60%;
    margin: 0 10px;
  }
  .el-button {
    height: 36px;
  }
}
.detail_wrap {
  margin-bottom: 0;
  overflow: hidden;
  transition-duration: 0.25s, 1s;
  ::v-deep .el-form-item__content {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
  }
}

.detail_add {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0px 0 20px;
  .el-button--medium {
    width: 40%;
  }
}
.toggle {
  margin: 0;
  padding: 0;
  span {
    color: #46a6ff;
    cursor: pointer;
  }
}

.price_wrap {
  ::v-deep .el-form-item__content {
    display: flex;
    flex-direction: column;
    .price {
      margin-bottom: 10px;
      span {
        width: 110px;
        display: inline-block;
      }
      span.el-input--suffix {
        margin-left: 100px;
      }
    }
  }
}
</style>
